var app=getApp();
var config = require('../../../../config.js');
var ux = require('../../../../lib/ux.js');
var animation;
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    aimg:'',
    dname:'',
    xname:'',  
    mobile:'',
    adressName:'',
    tiTime:'',
    tongyi:1, 
	action:"",
    province: {},
    city: {},
    area: {},
    country: {},
    animationAddressMenu: {},
    addressMenuIsShow: false,
    addressA: { address: '请选择坐标' },
    action: "/api/address/userAddressInfo.do",
    addUrl: "/api/address/userSaveAddress.do",
    editUrl: "/api/address/userEditAddress.do",
    pidUrl: "/api/address/pidAdderssList.do",
    getBaseData:"/api/delivery/deliveryGetInfos.do",
    submit:"{{submit}}"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 初始化动画变量
    var animation = wx.createAnimation({
      duration: 800,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;   
    var self=this;
    var pamas={};
    ux.request(self.data.getBaseData, pamas, function (protocol) {
      
      if (protocol.data.type==2){
        var dataObj = protocol.data.delivery;
      
        self.setData({
           id: dataObj.id,
          province: protocol.data.province,
          city: protocol.data.city,
          area: protocol.data.area,
          country: protocol.data.country,
           aimg: dataObj.shopPicture ? dataObj.shopPicture:'',
           dname: dataObj.name ? dataObj.name : '',
           xname: dataObj.contacts ? dataObj.contacts : '',
           mobile: dataObj.mobile ? dataObj.mobile : '',
           adressName: dataObj.address ? dataObj.address : '',
           tiTime: dataObj.deliveryTime ? dataObj.deliveryTime : '',
         })
        if (dataObj.coordinateAddress) {
          self.setData({
            addressA: { longitude: dataObj.longitude, latitude: dataObj.latitude, address: dataObj.coordinateAddress },
          })
        }
        }else{
        self.toast(protocol.data.msg);
        }
    }, true);
  },
  
  onForm:function(event){
	if(this.data.submit){
		  var $this = this;
		  var dataset = event.currentTarget.dataset;
		  ux.request(this.data.submit,detail.value,function(protocol){
				if(protocol.success){
					if(dataset.url){
						wx.redirectTo(dataset.url);
					}
				}
		  },true);
	 }
  },
  
  onTap:function(event){
	  var dataset = event.currentTarget.dataset;
	  var data = this.data;
	  if(dataset.key && dataset.val){
		  data[dataset.key] = dataset.val;
	  }
	  this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


  onChangeAddress: function (e) {
    wx.navigateTo({
      url: "/pages/member/tab3/adress/positon"
    });
  },
  tongyis: function () {
    if (this.data.tongyi == 2) {
      this.setData({
        tongyi: 1
      })
    } else {
      this.setData({
        tongyi: 2
      })
    }
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  chooseImage_attech: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var data = {};
        data.token = wx.getStorageSync('token') || "";
        data.timestamp = ux.formatTime(new Date());
        data.appid = config.appid;
        data.name = "test.jpg";
        data.sign = ux.getSign(config.secret, data);
        //上传服务器
        wx.uploadFile({
          url: config.apiUrl + '/api/upload/uploadimage.do',
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: data,
          header: {
            'content-type': 'multipart/form-data'
          }, // 设置请求的 header

          success: function (res1) {
            var data = JSON.parse(res1.data);
            if (data.data.type==1){
              that.toast(data.data.msg);
              that.setData({
                aimg: data.data.url
              })
           }
          },
          fail: function (res) {
            console.log(JSON.stringify(res));
            typeof fail == "function" && fail(res);
          }
        });
      }
    })
  },
  psgz:function(){
    wx.navigateTo({
      url: '/pages/protocol/psserver',
    })
  },
  shouyi: function () {
    wx.navigateTo({
      url: '/pages/protocol/shouyi',
    })
  },
  cityCancel:function(){
    // 执行显示动画
    this.startAddressAnimation(false)
  },
  citySure: function () {
    var that = this
    that.startAddressAnimation(false)
  },
  // 点击所在地区弹出选择框
  selectDistrict: function (e) {
    var that = this
    // 如果已经显示，不在执行显示动画
    if (that.data.addressMenuIsShow) {
      return
    }
    // 执行显示动画
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    console.log(isShow)
    var that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(100 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  getProvince: function () {
    var $this = this;
    var params = { pid: 0 }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 1,
        province: {},
        city: {},
        area: {},
        country: {}
      });
    }, true);
  },
  getCity: function () {
    var $this = this;
    var params = { pid: this.data.province.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 2,
        city: {},
        area: {},
        country: {}
      });
    }, true);
  },
  getArea: function () {
    var $this = this;
    var params = { pid: this.data.city.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 3,
        area: {},
        country: {}
      });
    }, true);
  },
  getCountry: function () {
    var $this = this;
    var params = { pid: this.data.area.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 4,
        country: {}
      });
    }, true);
  },
  selectThis: function (event) {
    var dataset = event.currentTarget.dataset;
    var lists = this.data.list;
    var index = dataset.index;
    if (this.data.thisType == 1) {
      this.setData({
        province: lists[index],
        thisColor: 1
      })
      this.getCity();
    } else if (this.data.thisType == 2) {
      this.setData({
        city: lists[index],
        thisColor: 2
      })
      this.getArea();
    } else if (this.data.thisType == 3) {
      this.setData({
        area: lists[index],
        thisColor: 3
      })
      this.getCountry();
    } else if (this.data.thisType == 4) {
      this.setData({
        country: lists[index],
        thisColor: 4
      })
    }

  },
  dname:function(e){
   this.setData({
     dname:e.detail.value
   })
  },
  xname: function (e) {
    this.setData({
      xname: e.detail.value
    })
  },
  mobile: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  adressName: function (e) {
    this.setData({
      adressName: e.detail.value
    })
  },
  tiTime: function (e) {
    this.setData({
      tiTime: e.detail.value
    })
  },
  tijiaos:function(){
    var self=this;
    if(!self.data.dname){
      self.toast("请输入店铺名称");
      return false;
    }
    if (!self.data.xname) {
      self.toast("请输入联系人");
      return false;
    }
    if (!self.data.mobile) {
      self.toast("请输入手机号");
      return false;
    }
    var regMobile = /^1\d{10}$/;
    if (!regMobile.test(self.data.mobile)) {
      self.toast("手机格式有误");
      return false;
    }
    if (!self.data.country.id) {
      wx.showToast({
        title: '选择详细所在地区',
      })
      return false;
    }
    if (!self.data.adressName) {
      self.toast("请输入详细地址");
      return false;
    }
    if (self.data.addressA.address == "请选择坐标") {
      wx.showToast({
        title: '请选择坐标',
      })
      return false;
    }
    if (!self.data.tiTime) {
      self.toast("请输入提货时间");
      return false;
    }
    if (!self.data.aimg) {
      self.toast("请上传店面照片");
      return false;
    }
    if (self.data.tongyi!=2) {
      self.toast("请同意规则及条款");
      return false;
    }
    var pamars = {
      longitude: this.data.addressA.longitude,
      latitude: this.data.addressA.latitude,
      coordinate: this.data.addressA.address,
      location: self.data.country.id,
      aimg: this.data.aimg,
      dname: this.data.dname,
      xname: this.data.xname,
      mobile: this.data.mobile,
      adressName: this.data.adressName,
      tiTime: this.data.tiTime,
    }
    var urls = "/api/delivery/editDistributors.do";
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(urls, pamars, function (protocol) {
      wx.hideLoading();
      self.toast("修改成功");
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页面
      var prevPage = pages[pages.length - 2]; //上一个页面
      wx.navigateBack({
        delta: 1
      })
    }, true)
  }
})
